package testmybatis.springmybatis;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;

import java.util.Set;

/**
 * @Description xxxMapper.class文件扫描器
 * @Author dangxianyue
 * @Date 2024/3/27 23:29
 */
public class MyMapperScanner extends ClassPathBeanDefinitionScanner {

    public MyMapperScanner(BeanDefinitionRegistry registry) {
        super(registry);
    }

    // 原来spring的scanner中，接口被认为不是bean，不会生成BeanDefinition，此处要重写
    @Override
    protected boolean isCandidateComponent(final AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface();
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(final String... basePackages) {
        final Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        for (final BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
            // 把BeanDefinition中的类型替换为FactoryBean
            final BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition();
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName());
            beanDefinition.setBeanClassName(MyMybatisFactoryBean.class.getName());
        }
        return beanDefinitionHolders;
    }
}
